<template>
  <el-card style="margin-bottom:20px;">
    <el-card shadow="hover">
      <div id="chartLineBox" style="width: 100%;height: 400px" />
    </el-card>
    <el-card v-if="isAdmin()" shadow="hover">
      <PieCharts ref="piechart" :request-flag="statsFlag" />
    </el-card>
  </el-card>
</template>
<script>
import { mapGetters } from 'vuex'
const { export_json_to_excel } = require('@/utils/vendor/Export2Excel')
const { getUserStatsData } = require('@/api/userstats')
import { getName, getUserCode } from '@/utils/auth'
import PieCharts from '../components/PieCharts'
const { getMenus } = require('@/utils/profileStatus')
export default {
  name: 'UserCharts',
  components: { PieCharts },
  data() {
    return {
      rolelist: [], // 用于存放当前登陆用户的角色信息
      statsFlag: false, // 是否通知饼状图组件发送请求获取数据
      dataSource: {}, // Echart数据集合 用于Excel表格
      option: {
        title: {
          text: '用户在线时长统计图',
          x: 'center'
        },
        tooltip: {
          trigger: 'axis',
          x: 'left'
        },
        toolbox: {
          show: true,
          feature: {
            dataView: {
              show: true,
              title: '数据视图',
              lang: ['数据视图', '关闭', '导出Excel'],
              contentToOption: function(element, opts) {
                console.log(opts)
                // 获取echarts数据
                var data = opts.series[0]
                // excel表头
                var tHead = ['用户', '日期', '在线时长/min']
                // excel表体
                var tData = []
                // excel文件名
                var tName = '用户' + getName() + '在线时长统计图' + new Date()
                // 循环添加excel表体, key需跟表头对应
                var currentUsername = getName()
                var dataIndex = data.data.length // 获取实际记录次数
                var key = data.time // 获取对应的记录时间
                var value = data.data // 获取记录的在线时长
                for (let i = 0; i < dataIndex; i++) {
                  tData.push({
                    '用户': currentUsername,
                    '日期': key[i],
                    '在线时长/min': value[i]
                  })
                }
                console.log(tData)
                // 导出
                const dataEx = tData.map(v => tHead.map(j => v[j]))
                console.log(dataEx)
                export_json_to_excel(tHead, dataEx, tName)
              }
            },
            restore: {
              show: true
            },
            dataZoom: {
              show: true
            },
            saveAsImage: {
              show: true
            },
            magicType: {
              type: ['bar', 'line']
            }

          }
        },
        legend: {

        },
        xAxis: { // x轴
          type: 'category',
          boundaryGap: true,
          data: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], // x轴下标 -- 日期 最近十条 或者 全部加载
          name: '日期',
          nameTextStyle: {
            fontSize: 16,
            padding: [0, 0, 0, 20]
          }
        },
        yAxis: {
          name: '在线时长/Min',
          nameTextStyle: {
            fontSize: 16,
            padding: [0, 0, 10, 0]
          },
          type: 'value'
        },
        // series: [{ name: 'aaa', data: [40, 69, 23, 32, 4, 23, 21, 64], type: 'line' },
        //   { name: 'bbb', data: [20, 63, 21, 23, 45, 256, 22, 64], type: 'line' }
        // ]
        series: [] // 数据源 可以设置多条进行对比，这里仅仅展示当前用户的信息统计图
      }
    }
  },
  computed: {
    ...mapGetters([
      'roles'
    ])
  },
  inject: ['reload'],
  mounted() {
    const rolelist = this.roles
    this.rolelist = rolelist
    this.getData()
  },
  methods: {
    getData() {
      this.getOnlineTimeLineData()
      // this.showPieData()
    },
    async getOnlineTimeLineData() {
      const res = await getUserStatsData('line', getUserCode()) // 可拓展为按照选项指定展示类型
      const data = res.data.main
      this.dataSource = res.data.main // 数据保存
      const header = res.data.respOutMsgHeader
      let dataArray = []
      dataArray.push(data)
      // Echart图的参数设置
      this.option.series = dataArray
      this.option.xAxis.data = data.time
      // 图表刷新
      this.chartChange()
      dataArray = []
      if (header.respCode === 200 && getMenus() === 'usercharts') {
        this.$message({
          type: 'success',
          iconClass: 'el-icon-loading',
          message: '用户在线时长统计信息刷新成功,刷新时间：' + header.respTime,
          duration: 1.5 * 1000
        })
      }
    },
    chartChange() {
      const myEcharts = this.$echarts.init(document.getElementById('chartLineBox'), 'vintge')
      // 使用刚刚指定的配置项和数据显示图表
      myEcharts.setOption(this.option, true)
    },
    // 更具角色信息判断是否展示饼状分析图
    isAdmin() {
      const adminRole = '超级管理员'
      const equalsRoleList = this.rolelist.filter(obj => obj.roleName === adminRole)
      if (equalsRoleList.length !== 0) {
        this.statsFlag = true // 设置子组件是否请求标志
        // this.showPieData()
        return true
      }
      return false
    },
    showPieData() {
      this.$refs.piechart.getDatas()
    }
  }
}
</script>

<style scoped>

</style>
